package com.hlhj.funlike_business.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.hlhj.funlike_business.CustView.RecyclerViewSpacesItemDecoration;
import com.hlhj.funlike_business.R;
import com.hlhj.funlike_business.activity.adapter.FoodAdp;
import com.hlhj.funlike_business.activity.adapter.SpecificationsAdp;
import com.hlhj.funlike_business.bean.BitmapEvent2;
import com.hlhj.funlike_business.bean.FoodDetailBean;
import com.hlhj.funlike_business.bean.FoodTypeBean;
import com.hlhj.funlike_business.bean.UpImgBean;
import com.hlhj.funlike_business.presenter.AddCommentyPresenter;
import com.hlhj.funlike_business.utils.FileUtils;
import com.hlhj.funlike_business.utils.MyFoodDialog;
import com.hlhj.funlike_business.utils.Tools;
import com.hlhj.funlike_business.utils.UpImgDialog;
import com.hlhj.funlike_business.views.AddCommentyView;
import com.huantansheng.easyphotos.EasyPhotos;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class AddCommentyAty extends BaseActivity<AddCommentyView, AddCommentyPresenter> implements AddCommentyView {

    private ImageView img_back;
    private TextView tv_title, tv_foodtype, tv_commit;
    private int type, id, type_id, num;
    private EditText edit_foodTitle, et_fooddetail, et_foodprice, et_limited, et_limited_discount;
    private CheckBox rb_btn1, rb_btn2, rb_btn3;
    private RecyclerView recycle_list, recycle_list1;
    private SpecificationsAdp specificationsAdp;
    private FoodAdp foodAdp;
    private List<FoodDetailBean.DataBean.AttrBean> attrBeans;
    private List<String> imgs;
    public static final int TAKE_PHOTO = 2;
    private UpImgDialog imgDialog;
    private List<FoodTypeBean.DataBean> optionsItems = new ArrayList<>();
    private List<String> optionsItems1 = new ArrayList<>();
    private MyFoodDialog myFoodDialog;

    private String good_name, food_detail, food_price, discount;
    //1非折扣 2折扣、是否限购 1非限购 2限购、是否热销 1非热销 2热销
    private int is_discount=1, is_restrictions=1, is_sell=1;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    protected int getContentId() {
        return R.layout.aty_addcommenty;
    }

    @Override
    protected void initData() {
        id = getIntent().getIntExtra("id", 0);
        type = getIntent().getIntExtra("type", 0);

        imgDialog = new UpImgDialog(this);
        myFoodDialog = new MyFoodDialog();
        imgs = new ArrayList<>();
        attrBeans = new ArrayList<>();
        if (type == 1) {
            tv_title.setText("编辑商品");
        } else {
            tv_title.setText("添加商品");
        }

        specificationsAdp = new SpecificationsAdp(this, attrBeans);
        recycle_list.setLayoutManager(new GridLayoutManager(this, 4));
        HashMap<String, Integer> stringIntegerHashMap = new HashMap<>();
        stringIntegerHashMap.put(RecyclerViewSpacesItemDecoration.TOP_DECORATION, 20);
        recycle_list.addItemDecoration(new RecyclerViewSpacesItemDecoration(stringIntegerHashMap));
        recycle_list.setAdapter(specificationsAdp);

        foodAdp = new FoodAdp(this, imgs);
        recycle_list1.setLayoutManager(new GridLayoutManager(this, 4));
        recycle_list1.setAdapter(foodAdp);
    }

    @NotNull
    @Override
    public AddCommentyView bindView() {
        return this;
    }

    @NotNull
    @Override
    public AddCommentyPresenter createPresenter() {
        return new AddCommentyPresenter();
    }

    @Override
    public void initView() {
        img_back = findViewById(R.id.img_back);
        tv_title = findViewById(R.id.tv_title);
        tv_foodtype = findViewById(R.id.tv_foodtype);
        edit_foodTitle = findViewById(R.id.edit_foodTitle);
        et_fooddetail = findViewById(R.id.et_fooddetail);
        et_foodprice = findViewById(R.id.et_foodprice);
        et_limited = findViewById(R.id.et_limited);
        et_limited_discount = findViewById(R.id.et_limited_discount);
        rb_btn1 = findViewById(R.id.rb_btn1);
        rb_btn2 = findViewById(R.id.rb_btn2);
        rb_btn3 = findViewById(R.id.rb_btn3);
        recycle_list = findViewById(R.id.recycle_list);
        recycle_list1 = findViewById(R.id.recycle_list1);
        tv_commit = findViewById(R.id.tv_commit);
    }


    @Override
    public void logicStart() {
        getPresenter().LoadFoodType(this);
        if (type == 1) {
            getPresenter().LoadFoodDetail(this, id);
        }

//        foodAdp.setListener(new FoodPhotoAdp.getDel() {
//            @Override
//            public void showDel(int position) {
//                imgs.remove(position);
//            }
//        });

        specificationsAdp.setListener(new SpecificationsAdp.getAddType() {
            @Override
            public void showAdd() {
                myFoodDialog.show(getFragmentManager(), "");
            }
        });

        myFoodDialog.setListener(new MyFoodDialog.AddFood() {
            @Override
            public void showGuiGe(String msg) {
                attrBeans.add(new FoodDetailBean.DataBean.AttrBean(0, msg.toString()));
                specificationsAdp.notifyDataSetChanged();
            }
        });
    }

    @Override
    public void setListener() {
        img_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        tv_foodtype.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showPickerView();
            }
        });
        edit_foodTitle.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                good_name = charSequence.toString();
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        et_fooddetail.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                food_detail = charSequence.toString();
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        rb_btn1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (rb_btn1.isChecked()) {
                    is_discount = 2;
                } else {
                    is_discount = 1;
                }
            }
        });
        rb_btn2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (rb_btn2.isChecked()) {
                    is_restrictions = 2;
                } else {
                    is_restrictions = 1;
                }
            }
        });
        rb_btn3.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (rb_btn3.isChecked()) {
                    is_sell = 2;
                } else {
                    is_sell = 1;
                }
            }
        });
        tv_commit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (null == good_name || "".equals(good_name) || TextUtils.isEmpty(good_name)) {
                    Toast.makeText(AddCommentyAty.this, "请输入商品名称", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (tv_foodtype.getText().toString().equals("") || TextUtils.isEmpty(tv_foodtype.getText())) {
                    Toast.makeText(AddCommentyAty.this, "请选择商品类型", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (null == food_detail || "".equals(food_detail) || TextUtils.isEmpty(food_detail)) {
                    Toast.makeText(AddCommentyAty.this, "请输入商品描述", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (null == et_foodprice.getText().toString() || "".equals(et_foodprice.getText().toString()) || TextUtils.isEmpty(et_foodprice.getText().toString())) {
                    Toast.makeText(AddCommentyAty.this, "请输入商品价格", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    food_price = et_foodprice.getText().toString();
                }
                if (is_discount == 2) {
                    if (null == et_limited.getText().toString() || "".equals(et_limited.getText().toString()) || TextUtils.isEmpty(et_limited.getText().toString())) {
                        Toast.makeText(AddCommentyAty.this, "请输入折扣", Toast.LENGTH_SHORT).show();
                        return;
                    } else {
                        discount = et_limited.getText().toString();
                    }
                } else {
                    discount = "0.0";
                }
                if (is_restrictions == 2) {
                    if (null == et_limited_discount.getText().toString() || "".equals(et_limited_discount.getText().toString()) || TextUtils.isEmpty(et_limited_discount.getText().toString())) {
                        Toast.makeText(AddCommentyAty.this, "请输入限量份数", Toast.LENGTH_SHORT).show();
                        return;
                    } else {
                        num = Integer.parseInt(et_limited_discount.getText().toString());
                    }
                } else {
                    num = 0;
                }

                String imgString = null;
                String appendString = new String();
                StringBuilder imgsBuilder = new StringBuilder();
                if (null != imgs && imgs.size() > 0) {
                    for (int i = 0; i < imgs.size(); i++) {
                        appendString = imgsBuilder.append("\"").append(imgs.get(i)).append("\"").append(",").toString();
                    }
                    imgString = new StringBuffer().append("[").append( appendString.substring(0,appendString.length()-1).toString()).append("]").toString();
                }

                StringBuilder stringBuffer = new StringBuilder();
                StringBuilder string = new StringBuilder();
                String append = new String();
                String attr = new String();
                if (null != attrBeans && attrBeans.size() > 0) {
                    for (int i = 0; i < attrBeans.size(); i++) {
                        int id = attrBeans.get(i).getId();
                        String name = attrBeans.get(i).getName();
                        append = stringBuffer.append("{").append("\"").append("id").append("\"").append(":").append("\"").append(id).append("\"").append(",")
                                .append("\"").append("name").append("\"").append(":").append("\"").append(name).append("\"").append("}").append(",").toString();
                    }

                    String pinjie = append.substring(0, append.length() - 1);
                    attr = string.append("[").append(pinjie).append("]").toString();
                }else {
                    attr=null;
                }


                Log.e("zy", "商品ID:" + id);
                Log.e("zy", "商品名称:" + good_name.toString());
                Log.e("zy", "商品类型:" + type_id);
                Log.e("zy", "价格:" + food_price.toString());
                Log.e("zy", "详情:" + food_detail.toString());
                Log.e("zy", "是否折扣：" + is_discount);
                Log.e("zy", "折扣：" + discount);
                Log.e("zy", "是否限量：" + is_restrictions);
                Log.e("zy", "限量数：" + num);
                Log.e("zy", "是否热销：" + is_sell);
                Log.e("zy", imgString.toString());
                Log.e("zy", attr.toString());
                if (type == 1) {
                    getPresenter().LoadEditFoodResult(AddCommentyAty.this, id, good_name, type_id, food_price
                            , food_detail, is_discount, discount, is_restrictions, num, is_sell, imgString, attr);
                } else {
                    getPresenter().LoadAddFood(AddCommentyAty.this, good_name, type_id, food_price, food_detail
                            , is_discount, discount, is_restrictions, num, is_sell, imgString, attr);
                }
            }
        });
    }

    public void showPickerView() {
        OptionsPickerView pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                String tx = optionsItems1.get(options1);
                type_id = optionsItems.get(options1).getId();
                tv_foodtype.setText(tx);
            }
        })
                .setTitleText("商品类型")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .build();

        pvOptions.setPicker(optionsItems1);//一级选择器
//        pvOptions.setPicker(options1Items, options2Items);//二级选择器
//        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    public void getBitmap(BitmapEvent2 bitmapEvent2) {
        try {
            File file = FileUtils.INSTANCE.createImageFile(bitmapEvent2.bitmap, this);
            imgDialog.show();
            getPresenter().LoadUpFoodImgResult(this, file);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != Activity.RESULT_OK) return;
        switch (requestCode) {
            case TAKE_PHOTO:
                ArrayList<String> listExtra = data.getStringArrayListExtra(EasyPhotos.RESULT_PATHS);
                File file = new File(listExtra.get(0).toString());
                imgDialog.show();
                getPresenter().LoadUpFoodImgResult(this, file);
                break;
        }
    }

    @Override
    public void showFoodDetai(FoodDetailBean.DataBean dataBean) {
        attrBeans.clear();
        attrBeans.addAll(dataBean.getAttr());
        specificationsAdp.notifyDataSetChanged();

        if (null != dataBean.getPhotos() && dataBean.getPhotos().size() >0){
            imgs.clear();
            for (String img : dataBean.getPhotos()) {
                imgs.add(img);
            }
            Log.e("zy", "商品照片：" + imgs.size());
            foodAdp.notifyDataSetChanged();
        }

        type_id = dataBean.getType_id();
        edit_foodTitle.setText(dataBean.getGoods_name());
        et_fooddetail.setText(dataBean.getDetails());
        et_foodprice.setText(dataBean.getDiscount_price());
        et_limited.setText(dataBean.getDiscount() + "");
        et_limited_discount.setText(dataBean.getNum() + "");
        is_discount = dataBean.getIs_discount();
        is_restrictions = dataBean.getIs_restrictions();
        is_sell = dataBean.getIs_sell();
        if (dataBean.getIs_discount() == 1) {
            rb_btn1.setChecked(false);
        } else {
            rb_btn1.setChecked(true);
        }
        if (dataBean.getIs_restrictions() == 1) {
            rb_btn2.setChecked(false);
        } else {
            rb_btn2.setChecked(true);
        }
        if (dataBean.getIs_sell() == 1) {
            rb_btn3.setChecked(false);
        } else {
            rb_btn3.setChecked(true);
        }
    }

    @Override
    public void showUpFoodImgResult(UpImgBean.DataBean dataBean) {
        Toast.makeText(AddCommentyAty.this, "上传成功", Toast.LENGTH_SHORT).show();
        imgs.add(dataBean.getUrl());
        foodAdp.notifyDataSetChanged();
        imgDialog.dismiss();
    }

    @Override
    public void showFoodType(List<FoodTypeBean.DataBean> dataBeans) {
        optionsItems.clear();
        optionsItems1.clear();
        for (int i = 0; i < dataBeans.size(); i++) {
            optionsItems1.add(dataBeans.get(i).getType_name());
        }
        optionsItems.addAll(dataBeans);
    }

    @Override
    public void showEditFoodResult(String msg) {
        Toast.makeText(AddCommentyAty.this, msg.toString(), Toast.LENGTH_SHORT).show();
        EventBus.getDefault().post(String.valueOf(id));
        finish();
    }
}
